/* eslint-disable react/no-unused-state */
import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row, Col, Card, Input, Table, Button, Divider, Modal,
} from 'antd';

import AddCabinet from '../components/addCabinet';

import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;
const { Item } = Form;
const { confirm } = Modal;

interface BankPaymentManageProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  screen: string;
}

interface BankPaymentManageState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  visible:boolean;
  record:object;
}

@connect(({ bankPayment: { dataInfo }, global: { screen }, loading }: any) => ({
  dataInfo,
  screen,
  loading: loading.effects['bankPayment/fetch'],
}))

class BankPaymentManageElem extends Component<BankPaymentManageProps, BankPaymentManageState> {
  columns = [
    {
      title: '柜体编号',
      dataIndex: 'cabCode',
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      render: (text: any, record: any) => text || '--',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
    },
    {
      title: '添加人',
      dataIndex: 'createUser',
    },
    {
      title: '操作',
      width: 140,
      dataIndex: 'id',
      render: (text: any, record: any) => (
        <div>
          <span className="operLink" onClick={() => this.addCabinet(record)}>编辑</span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.delete(record)}>删除</span>
        </div>
      ),
    },
  ];

  state: BankPaymentManageState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    visible: false,
    record: {},
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const {
      location: { query },
    } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;

    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();

    const { dataInfo } = this.props;
    if (dataInfo?.list?.length) return;

    this.fetchDataValues();
    this.fetchAction('common/fetchAreaList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (
      !_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue(searchValues);
  };

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  };

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '甘肃农信柜体支付管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const {
      form: { validateFieldsAndScroll },
    } = this.props;

    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const query = {
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '甘肃农信柜体支付管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const {
      form: { resetFields },
    } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '甘肃农信柜体支付管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0 ? typeName : `bankPayment/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  // 添加柜体
  addCabinet = (record:object) => {
    this.setState({
      visible: true,
      record,
    });
  };

  // 删除柜体
  delete = ({ id }: any) => {
    const _this = this;

    confirm({
      title: '确认删除该柜体吗?',
      onOk() {
        const search = _this.getQueryParams();
        _this.fetchAction('deleteCabinet', {
          params: { id },
          search,
        });
      },

    });
  }

  changVisible = (visible:boolean) => {
    this.setState({ visible: false });
    if (visible) this.fetchDataValues();
  }

  render() {
    const {
      pageIndex, pageSize, visible, record,
    } = this.state;

    const {
      dispatch,
      form: { getFieldDecorator },
      dataInfo,
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };
    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={6} sm={24}>
                <Item label="柜体编号" colon={false}>
                  {getFieldDecorator('cabCode')(
                    <Input allowClear placeholder="请输入" autoComplete="off" />,
                  )}
                </Item>
              </Col>
              <Col md={18} sm={24} className="flexFeView">
                <Button type="primary" htmlType="submit" className="smallButton">
                  查询
                </Button>
                <Button
                  className="addButton smallButton marginL16"
                  type="primary"
                  onClick={this.handleReset}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button className="smallButton" type="primary" size="small" onClick={() => this.addCabinet({})}>
              添加柜体
            </Button>
          </div>

          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
          />

        </Card>
        <AddCabinet
          visible={visible}
          dispatch={dispatch}
          record={record}
          changVisible={this.changVisible}
        />
      </>
    );
  }
}

export default Form.create<BankPaymentManageProps>()(BankPaymentManageElem);
